package com.doyled.jump.animation;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

public class TextAnimation_ extends Animation {

	private int x, y;
	private String fullText;
	private String text;
	private int numOfChar;
	private int beginIndex;
	private int endIndex;
	private int ratio;
	private Font defaultFont;

	public TextAnimation_(int x, int y) {
		this.x = x;
		this.y = y;
		defaultFont = new Font("Arial", Font.BOLD, 30);
	}

	public void setAnimation(int time, String text) {
		this.text = "";
		this.numOfChar = text.length();
		this.fullText = getEmptyText(numOfChar) + text;
		this.second = time;
		this.totalFrames = 60 * this.second;
		this.frame = 0;
		this.animatingFlag = true;
		this.beginIndex = -1;
		this.endIndex = beginIndex + numOfChar;
		this.ratio = (totalFrames / 2) / numOfChar;
	}

	private String getEmptyText(int numOfChar) {
		String text = "";
		for (int i = 0; i < numOfChar; i++) {
			text += " ";
		}
		return text;
	}

	/**
	 * animating in a specific set time animatingFlag is true for animating and
	 * animatingFlag is false for not animating
	 */
	@Override
	public void tick() {
		if (this.animatingFlag == true) {
			if (frame < totalFrames / 2) {
				if (frame % ratio == 0) {
					if (endIndex < fullText.length()) {
						beginIndex++;
						endIndex = beginIndex + numOfChar;
					}
					text = fullText.substring(beginIndex, endIndex);
				}
				frame++;
			} else if (frame < totalFrames) {
				if (frame % ratio == 0) {
					if (beginIndex > 0) {
						endIndex--;
						beginIndex = endIndex - numOfChar;
					}
					text = fullText.substring(beginIndex, endIndex);
				}
				frame++;
			} else {
				this.animatingFlag = false;
			}
		}
	}

	@Override
	public void render(Graphics g) {
		int width = g.getFontMetrics(defaultFont).stringWidth(text);
		int height = g.getFontMetrics(defaultFont).getHeight();
		int realX = x - width / 2;
		int realY = y - height / 2;
		g.setColor(Color.RED);
		g.setFont(defaultFont);
		g.drawString(text, realX, realY);
	}
}
